package org.wishwork.api.order.query;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.order.query.response.OrderQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 订单查询
 * @author: WangYX
 * @create: 2022-04-13 10:26
 * @Version: 1.0.0
 **/

public class OrderQueryApi extends Api<List<OrderQueryResponse>, OrderQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(OrderQueryApi.class);

    private Context context;

    public OrderQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(OrderQueryRequest orderQueryRequest) throws Exception {
        String url = "/open/orders/single/query";
        Map<String, Object> params = new HashMap<>();
        if (orderQueryRequest.getShopId() != null) {
            params.put("shop_id", orderQueryRequest.getShopId());
        }
        if (ObjectUtil.isNotEmpty(orderQueryRequest.getIsOfflineShop())) {
            params.put("is_offline_shop", orderQueryRequest.getIsOfflineShop());
        }
        if (orderQueryRequest.getSoIds() != null && orderQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", orderQueryRequest.getSoIds());
        }
        if (StrUtil.isNotEmpty(orderQueryRequest.getStatus())) {
            params.put("status", orderQueryRequest.getStatus());
        }
        return HttpHelper.sendRequest(params, url);
    }

    @Override
    protected List<OrderQueryResponse> process(JSONObject data, OrderQueryRequest orderQueryRequest) throws Exception {
        JSONArray orders = data.getJSONArray("orders");
        List<OrderQueryResponse> orderQueryResponses = orders.toJavaList(OrderQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = orderQueryRequest.getPageIndex();
            OrderQueryRequest build = orderQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<OrderQueryResponse> business = business(build);
            orderQueryResponses.addAll(business);
        }
        return orderQueryResponses;
    }
}
